﻿using System;
using System.Text;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Utilities;
using System.Web.UI.WebControls;

namespace Rtl.SharePoint.WebControls
{
    public class VEAddressEditor : EntityEditorWithPicker
    {
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            base.PickerDialogType = typeof(VEAddressPicker);
            //base.AllowTypeIn = false;
            base.MultiSelect = false;
        }

        public void RegisterPostCallbackScript()
        {
            const string SCRIPT_REG_NAME = "__CallBack__RtlUSAddressEntityEditorCallback";
            if (!this.Page.ClientScript.IsClientScriptBlockRegistered(this.GetType(), SCRIPT_REG_NAME))
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("<script language=\"javascript\">\r\n");
                sb.Append("    function RtlUSAddressEntityEditorCallback(xml,ctrlAddress,ctrlCity,ctrlState,ctrlZip,ctrlLat,ctrlLong) {\r\n");
                sb.Append("        if (xml == null) {\r\n");
                sb.Append("            return;\r\n");
                sb.Append("        }\r\n");
                sb.Append("        var xmlDoc;\r\n");
                sb.Append("        if (document.implementation && document.implementation.createDocument) {\r\n");
                sb.Append("            xmlDoc = (new DOMParser()).parseFromString(xml, \"text/xml\");\r\n");
                sb.Append("        }\r\n");
                sb.Append("        else {\r\n");
                sb.Append("            xmlDoc = new ActiveXObject(\"Microsoft.XMLDOM\");\r\n");
                sb.Append("            xmlDoc.async = false;\r\n");
                sb.Append("            xmlDoc.loadXML(xml);\r\n");
                sb.Append("        }\r\n");
                sb.Append("        if (xmlDoc.documentElement == null) {\r\n");
                sb.Append("            return;\r\n");
                sb.Append("        }\r\n");
                sb.Append("        var entities = xmlDoc.documentElement;\r\n");
                sb.Append("        var nodeSetEntryData = entities.getElementsByTagName(\"DictionaryEntry\");\r\n");
                sb.Append("        var key, val;\r\n");
                sb.Append("        for (i = 0; i < nodeSetEntryData.length; i++) {\r\n");
                sb.Append("            key = nodeSetEntryData[i].getElementsByTagName(\"Key\")[0];\r\n");
                sb.Append("            val = nodeSetEntryData[i].getElementsByTagName(\"Value\")[0];\r\n");
                sb.Append("            switch (key.text) {\r\n");
                sb.Append("                case \"Address\":\r\n");
                sb.Append("                    var storAddress = document.getElementById(ctrlAddress);\r\n");
                sb.Append("                    if (storAddress != null)\r\n");
                sb.Append("                        storAddress.value = val.text;\r\n");
                sb.Append("                    break;\r\n");
                sb.Append("                case \"City\":\r\n");
                sb.Append("                    var storCity = document.getElementById(ctrlCity);\r\n");
                sb.Append("                    if (storCity != null)\r\n");
                sb.Append("                        storCity.value = val.text;\r\n");
                sb.Append("                    break;\r\n");
                sb.Append("                case \"State\":\r\n");
                sb.Append("                    var storState = document.getElementById(ctrlState);\r\n");
                sb.Append("                    if (storState != null)\r\n");
                sb.Append("                        storState.value = val.text;\r\n");
                sb.Append("                    break;\r\n");
                sb.Append("                case \"Zip\":\r\n");
                sb.Append("                    var storZip = document.getElementById(ctrlZip);\r\n");
                sb.Append("                    if (storZip != null)\r\n");
                sb.Append("                        storZip.value = val.text;\r\n");
                sb.Append("                    break;\r\n");
                sb.Append("                case \"Longitude\":\r\n");
                sb.Append("                    var storLong = document.getElementById(ctrlLong);\r\n");
                sb.Append("                    if (storLong != null)\r\n");
                sb.Append("                        storLong.value = val.text;\r\n");
                sb.Append("                    break;\r\n");
                sb.Append("                case \"Latitude\":\r\n");
                sb.Append("                    var storLat = document.getElementById(ctrlLat);\r\n");
                sb.Append("                    if (storLat != null)\r\n");
                sb.Append("                        storLat.value = val.text;\r\n");
                sb.Append("                    break;\r\n");
                sb.Append("            }\r\n");
                sb.Append("        }\r\n");
                sb.Append("    }\r\n");
                sb.Append("</script>\r\n");

                this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), SCRIPT_REG_NAME, sb.ToString());
            }
        }

        private string BuildClientCallbackWrapper()
        {
            string registrationName = "__CallBackWrapper__" + this.ClientID;
            string functionName = "AddressEditorCallback_" + SPHttpUtility.EcmaScriptStringLiteralEncode(this.ClientID);

            this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), registrationName, "<script language=\"javascript\">function " + functionName + "(ctx,xml) { " + this.GenerateCustomCallback() + " } </script>");

            return functionName;
        }

        protected override void OnPreRender(EventArgs e)
        {
            RegisterPostCallbackScript();
            base.AfterCallbackClientScript = BuildClientCallbackWrapper();
            base.OnPreRender(e);

            base.UpLevelDiv.Style.Add(System.Web.UI.HtmlTextWriterStyle.Display, "none");
            base.DownLevelTextBox.Style.Add(System.Web.UI.HtmlTextWriterStyle.Display, "none");

            TableCell cell = base.UpLevelDiv.Parent as TableCell;
            if (cell != null)
            {
                cell.Style.Add(System.Web.UI.HtmlTextWriterStyle.Display, "none");
            }

            HyperLink checkNames = base.FindControl("checkNames") as HyperLink;
            if (checkNames != null)
            {
                checkNames.Style.Add(System.Web.UI.HtmlTextWriterStyle.Display, "none");
            }
        }

        internal string GenerateCustomCallback()
        {
            USAddressFieldControl ctrlParent = this.AddressControl as USAddressFieldControl;
            
            string strDivId = base.UpLevelDiv.ClientID != null ? SPHttpUtility.EcmaScriptStringLiteralEncode(base.UpLevelDiv.ClientID) : string.Empty;
            string strAddId = string.Empty;
            string strCityId = string.Empty;
            string strStateId = string.Empty;
            string strZipId = string.Empty;
            string strLatId = string.Empty;
            string strLongId = string.Empty;

            if (ctrlParent != null)
            {
                strAddId = ctrlParent.Street1TextBox != null ? SPHttpUtility.EcmaScriptStringLiteralEncode(ctrlParent.Street1TextBox.ClientID) : string.Empty;
                strCityId = ctrlParent.CityTextBox != null ? SPHttpUtility.EcmaScriptStringLiteralEncode(ctrlParent.CityTextBox.ClientID) : string.Empty;
                strStateId = ctrlParent.StateDropDown != null ? SPHttpUtility.EcmaScriptStringLiteralEncode(ctrlParent.StateDropDown.ClientID) : string.Empty;
                strZipId = ctrlParent.ZipTextBox != null ? SPHttpUtility.EcmaScriptStringLiteralEncode(ctrlParent.ZipTextBox.ClientID) : string.Empty;
                strLatId = ctrlParent.LatitudeField != null ? SPHttpUtility.EcmaScriptStringLiteralEncode(ctrlParent.LatitudeField.ClientID) : string.Empty;
                strLongId = ctrlParent.LongitudeField != null ? SPHttpUtility.EcmaScriptStringLiteralEncode(ctrlParent.LongitudeField.ClientID) : string.Empty;
            }

            return "RtlUSAddressEntityEditorCallback(xml,'" +
                strAddId + "','" +
                strCityId + "','" +
                strStateId + "','" +
                strZipId + "','" +
                strLatId + "','" +
                strLongId + "');";
        }

        private USAddressFieldControl _addressControl;
        public USAddressFieldControl AddressControl
        {
            get { return _addressControl; }
            set { _addressControl = value; }
        }
    }
}
